/*******************************************************************************
 * Copyright (c) 2009 Kevin Bierhoff and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Kevin Bierhoff - initial API and implementation
 *******************************************************************************/
package com.googlecode.twelfdevtools.twelfast;

import java.util.LinkedList;

public class Arrow implements ITwelfTerm {
	
	/**
	 * Creates nested {@link Arrow} objects based on the given
	 * term list, respecting the right-associativity of 
	 * the right arrow operator.
	 * @param stack must be non-empty.
	 * @return Nested Arrow objects or the only element contained in <code>stack</code>.
	 */
	public static ITwelfTerm forwArr(LinkedList<ITwelfTerm> stack) {
		if(stack.isEmpty())
			throw new IllegalArgumentException("Must provide non-empty stack");
		ITwelfTerm t = stack.removeLast();
		while(!stack.isEmpty()) {
			t = new Arrow(stack.removeLast(), t);
		}
		return t;
	}

	public static Arrow forwArr(ITwelfTerm t1, ITwelfTerm t2) {
		return new Arrow(t1, t2);
	}

	public static Arrow backArr(ITwelfTerm t1, ITwelfTerm t2) {
		return new Arrow(t2, t1);
	}

	private ITwelfTerm lhs;
	private ITwelfTerm rhs;
	
	public Arrow(ITwelfTerm lhs, ITwelfTerm rhs) {
		super();
		this.lhs = lhs;
		this.rhs = rhs;
	}

	public ITwelfTerm getLhs() {
		return lhs;
	}

	public ITwelfTerm getRhs() {
		return rhs;
	}

	public <T> T dispatch(ITwelfAstVisitor<T> visitor) {
		return visitor.arrow(this);
	}

	@Override
	public String toString() {
		return "(" + lhs + " -> " + rhs + ")";
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((lhs == null) ? 0 : lhs.hashCode());
		result = prime * result + ((rhs == null) ? 0 : rhs.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Arrow other = (Arrow) obj;
		if (lhs == null) {
			if (other.lhs != null)
				return false;
		} else if (!lhs.equals(other.lhs))
			return false;
		if (rhs == null) {
			if (other.rhs != null)
				return false;
		} else if (!rhs.equals(other.rhs))
			return false;
		return true;
	}

}
